package com.birdboot.core;

import com.birdboot.annotations.Controller;
import com.birdboot.annotations.RequestMapping;
import com.birdboot.controller.UserController;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 *
 * */
public class DispatcherServlet {
    //单例模式
    private static DispatcherServlet instance = new DispatcherServlet();
    private DispatcherServlet(){}
    public static DispatcherServlet getInstance(){ return instance; }

    private static File baseDir;
    private static File staticDir;
    static {
        try {
            baseDir = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(baseDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void service(HttpServletRequest request, HttpServletResponse response)  {
        String path = request.getRequestURI();
        System.out.println("抽象路径"+path);

        try {
            File dir = new File(baseDir,"com/birdboot/controller");
            File [] subs = dir.listFiles(f -> f.getName().contains(".class"));
            for (File sub: subs
            ) {
                String fileName = sub.getName();
                String className = fileName.substring(0,fileName.indexOf("."));
                Class cls = Class.forName("com.birdboot.controller."+className);
                if(cls.isAnnotationPresent(Controller.class)){
                    Method [] methods = cls.getDeclaredMethods();
                    for (Method method:methods) {
                        if(method.isAnnotationPresent(RequestMapping.class)){
                            if (method.getAnnotation(RequestMapping.class).value().equals(path)){
                                Object obj = cls.newInstance();
                                //cls.getMethod(method.getName(),request.getClass(),response.getClass()).invoke(obj,request,response);
                                method.invoke(obj,request,response);
                                return;
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        File file = new File(staticDir,path);
        if(!file.isFile()){
            file = new File(staticDir,"404.html");
            response.setStatusCode(404);
            response.setStatusReason("Not Found");
            response.addHeader("Server","BirdServer");
        }else {
            response.addHeader("Server","BirdServer");
        }
        response.setContentFile(file);
    }
}
